package com.yc.atm;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.log4j.Logger;

import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.net.Socket;
import java.util.Scanner;

public class AtmClient {

    private static Logger log = Logger.getLogger(AtmClient.class.getName());
    private Socket s;
    Scanner keyboard = new Scanner(System.in);
    public static void main(String[] args) {
        String host = "localhost";
        int port=10082;
        Scanner keyboard = new Scanner(System.in);//键盘
        boolean flag=true;
        try (
                Socket s = new Socket(host,port);
                Scanner sc = new Scanner(s.getInputStream());//读取服务器的响应
                PrintWriter pw = new PrintWriter(s.getOutputStream())//可以一行一行读取
        ) {
            log.info("联接服务器"+s.getRemoteSocketAddress()+"成功");
            do {
                System.out.println("*******************中国银行ATM欢迎您的光临*****************");
                System.out.println("1.存");
                System.out.println("2.取");
                System.out.println("3.查询");
                System.out.println("4.退出");
                System.out.println("5.错误命令(美哟有命令)");
                System.out.println("******************");
                System.out.println("请输入您的操作选项");
                String command =keyboard.nextLine();
                String response =null;
                if ("1".equalsIgnoreCase(command)) {
                    pw.println("DEPOSIT 1 100");
                } else if ("2".equalsIgnoreCase(command)) {
                    pw.println("WITHDRAW 1 10");
                }else if ("3".equalsIgnoreCase(command)) {
                    pw.println("BALANCE 1");
                }else if ("5".equalsIgnoreCase(command)) {
                    pw.println("adfdsf");
                }else {
                    pw.println("QUIT");
                    pw.flush();
                    flag =false;
                    break;
                }
                pw.flush();
                //取服务器的响应
                response = sc.nextLine();
                System.out.println("服务器的响应"+response);
                Gson gson =new Gson();
                //设定gson处理字符串数据的类型   ： vue   axios
                Type type = new TypeToken<JsonModel <BankAccount> >(){}.getType();
                JsonModel<BankAccount> jm = gson.fromJson(response,type);
                if (jm.getCode() == 1) {
                    BankAccount ba = jm.getObj();
                    System.out.println(ba.getId() + "\t" + ba.getBalance());
                } else {
                    System.out.println(jm.getError());
                }
            } while (true);
            System.out.println("Atm机退出当前帐号，程序结束");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //printlin() 可以一行的发送数据
}
